package com.luzhikun.myshopping.controller;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "FileUploadServlet", value = "/fileUploadServlet")
public class FileUploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取工厂
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload();
        upload.setHeaderEncoding("utf-8");
        upload.setFileItemFactory(factory);
        // 解析请求
        try {
            List<FileItem> fileItems = upload.parseRequest(request);
            String realPath = request.getServletContext().getRealPath("/upload/");
            System.out.println(realPath);
            for (FileItem f : fileItems) {
                if (f.isFormField()) {
                    String fieldName = f.getFieldName();
                    System.out.println(fieldName + "==" + f.getString());
                } else {
                    File file = new File(realPath, f.getName() );
                    f.write(file);
                    f.delete();
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}
